package cn.laixueit.cart.service;

import cn.laixueit.cart.client.GoodsClient;
import cn.laixueit.cart.interceptor.LoginInterceptor;
import cn.laixueit.cart.pojo.Cart;
import cn.laixueit.entity.UserInfo;
import cn.laixueit.pojo.item.Sku;
import cn.laixueit.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    private final  String KEY_PREFIX = "user:cart:uid:";

    public void cart(Cart cart) {
        //判断redis中是否存在该商品，存在修改数量
        // 因为存储类型的原，所以需要先获取当前登录的用户
        UserInfo userInfo = LoginInterceptor.getLogin();

        String key =  KEY_PREFIX +userInfo.getId();

        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(key);
        
        // 获取是否存在该商品
        Boolean boo = boundHashOps.hasKey(cart.getSkuId().toString());

        Integer num = cart.getNum();

        if(boo){
            //存在，修改数量
//            获取购物车
            String json = boundHashOps.get(cart.getSkuId().toString()).toString();
            cart = JsonUtils.parse(json,Cart.class);
            cart.setNum(cart.getNum()+num);
        }else{
            // 不存在，添加
            cart.setUserId(userInfo.getId());
            // 其它商品信息，需要查询商品服务
            Sku sku = goodsClient.getSkuById(cart.getSkuId()).getBody();
            cart.setImage(sku.getImages().split(",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
        }
        // 重新塞回去
        boundHashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart) );
    }

    public List<Cart> listCart() {
        UserInfo userInfo = LoginInterceptor.getLogin();
        String key = KEY_PREFIX + userInfo.getId();
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
        List<Object> carts = hashOps.values();
        if(CollectionUtils.isEmpty(carts)){
            return null;
        }
        List<Cart> cartList = carts.stream().map(o -> JsonUtils.parse(o.toString(), Cart.class)).collect(Collectors.toList());
        return cartList;
    }
}
